#!/bin/sh
## java env
export JAVA_HOME=/data/java/jdk1.8.0_162
export JRE_HOME=$JAVA_HOME/jre

APP_NAME=magic4j-application-stage-1.0

JAR_NAME=$APP_NAME\.jar

PID=$APP_NAME\.pid

usage() {
    echo "Usage: sh fileName.sh [start|stop|restart|status]"
    exit 1
}


is_exist(){
  pid=`ps -ef|grep $JAR_NAME|grep -v grep|awk '{print $2}' `   
  if [ -z "${pid}" ]; then
   return 1
  else
    return 0
  fi
}


start(){
  is_exist
  if [ $? -eq "0" ]; then 
    echo ">>> ${JAR_NAME} is already running PID=${pid} <<<" 
  else 
    nohup $JRE_HOME/bin/java -Xms512m -Xmx512m -verbose:gc -Xloggc:/data/htdocs/logs/jvm/$API_NAME-gc.log -XX:+UseConcMarkSweepGC -XX:+HeapDumpOnOutOfMemoryError -XX:+PrintHeapAtGC -XX:HeapDumpPath=/mydata/htdocs/logs/jvm/$API_NAME-dump.hprof -XX:+PrintGCApplicationStoppedTime -XX:+PrintGCTimeStamps -XX:+PrintCommandLineFlags -XX:+PrintFlagsFinal -XX:+PrintGCDetails -XX:+UseCMSCompactAtFullCollection -jar $JAR_NAME --SERVER_PORT="8888" --SWAGGER_ENABLE="true"  --DATASOURCE_URL="127.0.0.1:3306/magic4j" --DATASOURCE_USERNAME="magic4jUser" --DATASOURCE_PASSWORD="magic4j@srG123" --CACHE_TYPE="redis" >/dev/null 2>&1 &
    echo $! > $PID
    echo ">>> start $JAR_NAME successed PID=$! <<<" 
   fi
  }


stop(){

  pidf=$(cat $PID)
  echo ">>> api PID = $pidf begin kill $pidf <<<"
  kill $pidf
  rm -rf $PID
  sleep 2
  is_exist
  if [ $? -eq "0" ]; then 
    echo ">>> api 2 PID = $pid begin kill -9 $pid  <<<"
    kill -9  $pid
    sleep 2
    echo ">>> $JAR_NAME process stopped <<<"  
  else
    echo ">>> ${JAR_NAME} is not running <<<"
  fi  
}

status(){
  is_exist
  if [ $? -eq "0" ]; then
    echo ">>> ${JAR_NAME} is running PID is ${pid} <<<"
  else
    echo ">>> ${JAR_NAME} is not running <<<"
  fi
}

restart(){
  stop
  start
}

case "$1" in
  "start")
    start
    ;;
  "stop")
    stop
    ;;
  "status")
    status
    ;;
  "restart")
    restart
    ;;
  *)
    usage
    ;;
esac
exit 0
